package com.example.logistics.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.logistics.pojo.entity.WuLiu;
import com.example.logistics.repository.JpaWuLiuRepository;
import com.example.logistics.service.WuLiuService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.List;

@Service
public class WuLiuServiceImpl implements WuLiuService {
    @Resource
    JpaWuLiuRepository jpaSuSheRepository;


    @Override
    public Page<WuLiu> listData(Integer pageSize, Integer currentPage, String searchCol, String searchText) {
        PageRequest pageRequest = PageRequest.of(currentPage-1, pageSize);
        Specification<WuLiu> specification = new Specification<WuLiu>() {
            @Override
            public Predicate toPredicate(Root<WuLiu> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                // 动态 SQL表达式
                Predicate conjunction = criteriaBuilder.conjunction();
                // 动态 SQL表达式集合
                List<Expression<Boolean>> expressions = conjunction.getExpressions();
                if(StrUtil.isNotBlank(searchCol)&& StrUtil.isNotBlank(searchText)){
                    expressions.add(criteriaBuilder.like(root.get(searchCol).as(String.class),"%"+searchText+"%"));
                }
                return conjunction;
            }
        };

        if(StrUtil.isNotBlank(searchCol)&& StrUtil.isNotBlank(searchText)){
            Page<WuLiu> all = jpaSuSheRepository.findAll(specification,pageRequest);
            return all;
        }

        Page<WuLiu> all = jpaSuSheRepository.findAll(specification,pageRequest);
        return all;

    }

    @Override
    public void add(WuLiu addForm) {
        WuLiu save = jpaSuSheRepository.save(addForm);
    }

    @Override
    public void update(WuLiu addForm) {
        jpaSuSheRepository.save(addForm);
    }

    @Override
    public void delete(Integer id) {
        WuLiu wuLiu = new WuLiu();
        wuLiu.setId(id);
        jpaSuSheRepository.delete(wuLiu);
    }
}
